<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Settings_crud {

    var $total_tables = array();

    public function __construct() {
        $this->CI = & get_instance();
        $this->CI->config->load('database_tables');
        $this->total_tables = $this->CI->config->item('dbtables');
    }

    public function get_columns_table($tabla = null, $extras = array()) {
        $columnas = array();
        $query = $this->CI->db->get_where($this->total_tables['crud_tablas'], array('nombre' => $tabla));
        if ($query->num_rows() > 0) {
            $row = $query->row_array();
            $query = $this->CI->db->get_where($this->total_tables['crud_campos'], array('fk_id_' . $this->total_tables['crud_tablas'] => $row['id'], 'visible_vista' => 1));
            foreach ($query->result_array() as $value) {
                $columnas[] = $value['nombre'];
            }
        }
        return array_merge($columnas, $extras);
    }

    public function get_columns_form($tabla = null, $extras = array()) {
        $columnas = array();
        $query = $this->CI->db->get_where($this->total_tables['crud_tablas'], array('nombre' => $tabla));
        if ($query->num_rows() > 0) {
            $row = $query->row_array();
            $query = $this->CI->db->get_where($this->total_tables['crud_campos'], array('fk_id_' . $this->total_tables['crud_tablas'] => $row['id'], 'visible_form' => 1));
            foreach ($query->result_array() as $value) {
                $columnas[] = $value['nombre'];
                if ($value['nombre'] == 'password') {
                    $columnas[] = 'password_confirm';
                }
            }
        }
        return array_merge($columnas, $extras);
    }

    public function get_values_form($tabla = null, $extras = array()) {
        $columnas = array();
        $query = $this->CI->db->get_where($this->total_tables['crud_tablas'], array('nombre' => $tabla));
        if ($query->num_rows() > 0) {
            $row = $query->row_array();
            $query = $this->CI->db->get_where($this->total_tables['crud_campos'], array('fk_id_' . $this->total_tables['crud_tablas'] => $row['id'], 'visible_form' => 1));
            foreach ($query->result_array() as $value) {
                $columnas[] = $value['nombre'];
            }
            $this->CI->db->select(array_merge($columnas, $extras));
            $query = $this->CI->db->get_where($tabla, array('id' => $this->CI->session->userdata('product_id')));
            $valores = array();
            foreach ($query->result_array() as $value) {
                for ($x = 0; $x < count($columnas); $x++) {
                    $valores[] = $value[$columnas[$x]];
                }
            }
        }
        return $valores;
    }
}